package com.cgc.venus.server.job.jobdetail;
import com.cgc.venus.server.core.harbor.client.HarborClient;
import com.cgc.venus.server.core.k8s.impl.K8sManageServiceImpl;
import com.cgc.venus.server.core.k8s.inter.K8sManageService;
import com.cgc.venus.server.core.utils.SpringUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import com.cgc.venus.server.job.Constants;
import com.cgc.venus.server.job.config.JobConfig;
import com.cgc.venus.server.job.service.CIServiceImpl;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.utils.HttpClientUtils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 统计平台健康
 */
public class StatsHealthJob extends AbstractBaseJob {
    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    private static Logger logger = LoggerFactory.getLogger(StatsHealthJob.class);
    public StatsHealthJob() {
    }
    public void execute(JobExecutionContext context)  
        throws JobExecutionException {
        logger.info("统计平台健康job start...");
        List objs = new ArrayList<Object>();
        String sql="";
        String id=null;
        try {
            OkHttpClient httpClient  = new OkHttpClient.Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .readTimeout(5, TimeUnit.SECONDS)
                    .build();
            //查询统计信息
            int Status_k8s=1;
            int Status_harbor=1;
            int Status_jenkins=1;
            int Status_user_center=1;
            int Status_app_center=1;
            int Status_monitor_center=1;
            int Status_log_center=1;
            int Status_job_center=1;
            int Status_ci_center=1;
            int Status_help_center=1;
            int Status_apiroute=1;
            String result="";
            //k8s组件服务健康检查
            try {
                KubernetesClient k8sClient=SpringUtil.getBean(K8sManageServiceImpl.class).getK8sClient();
                URL url =k8sClient.getMasterUrl();//https://10.10.40.235:23232/
                OkHttpClient okHttpClient= HttpClientUtils.createHttpClient(k8sClient.getConfiguration());
                String masterUrl=url.toString();
                result=getResult(masterUrl+"healthz",okHttpClient);
                if(!"ok".equals(result)){
                    Status_k8s=0;
                }
            }catch (KubernetesClientException ex){
                logger.error(ex.getMessage(),ex);
                Status_k8s=0;
            }
            //harbor组件服务健康检查
            try {
                SpringUtil.getBean(HarborClient.class).search("");
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_harbor=0;
            }

            //jenkins组件服务健康检查
            try {
                SpringUtil.getBean(CIServiceImpl.class).getJenkinsServer();
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_jenkins=0;
            }

            JobConfig jobConfig=SpringUtil.getBean(JobConfig.class);
            String routeApiURl=jobConfig.getRouteApiUrl(); //eg.http://localhost:5000
            String url="";
            //用户中心组件服务健康检查
            try {
                url=routeApiURl+"/api-user/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_user_center=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_user_center=0;
            }
            //应用中心组件服务健康检查
            try {
                url=routeApiURl+"/api-app/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_app_center=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_app_center=0;
            }
            //监控中心组件服务健康检查
            try {
                url=routeApiURl+"/api-monitor/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_monitor_center=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_monitor_center=0;

            }
            //日志中心组件服务健康检查
            try {
                url=routeApiURl+"/api-log/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_log_center=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_log_center=0;
            }

            //CICD中心组件服务健康检查
            try {
                url=routeApiURl+"/api-ci/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_ci_center=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_ci_center=0;
            }
            //任务中心组件服务健康检查
            try {
//                url=routeApiURl+"/api-job/health";
//                result=getResult(url,httpClient);
//                if(result.indexOf("UP")==-1){
//                    Status_job_center=0;
//                }
            }catch (Exception ex){
//                logger.error(ex.getMessage(),ex);
//                Status_job_center=0;
            }

            //路由中心组件服务健康检查
            try {
                url=routeApiURl+"/health";
                result=getResult(url,httpClient);
                if(result.indexOf("UP")==-1){
                    Status_apiroute=0;
                }
            }catch (Exception ex){
                logger.error(ex.getMessage(),ex);
                Status_apiroute=0;
            }

            String alertMsg="";
            if(Status_k8s==0){
                alertMsg+=",k8s组件服务异常";
            }
            if(Status_harbor==0){
                alertMsg+=",harbor组件服务异常";
            }
            if(Status_jenkins==0){
                alertMsg+=",jenkins组件服务异常";
            }
            ////
            if(Status_user_center==0){
                alertMsg+=",用户中心组件服务异常";
            }
            if(Status_app_center==0){
                alertMsg+=",应用中心组件服务异常";
            }
            if(Status_monitor_center==0){
                alertMsg+=",监控组件服务异常";
            }
            if(Status_log_center==0){
                alertMsg+=",日志组件服务异常";
            }
            if(Status_job_center==0){
                alertMsg+=",任务组件服务异常";
            }
            if(Status_ci_center==0){
                alertMsg+=",CICD组件服务异常";
            }
            if(Status_help_center==0){
                alertMsg+=",帮助中心组件服务异常";
            }
            if(Status_apiroute==0){
                alertMsg+=",路由中心组件服务异常";
            }
            //处理告警
            if(!alertMsg.equals("")){
                //往告警表插入一条记录
                alertMsg=alertMsg.substring(1);
                handleEx(alertMsg, Constants.ALARM_TYPE_HEALTH, Constants.ALARM_STATUS_UN, Constants.ALARM_LEVEL_HIGHEST, Constants.ALARM_NS_ALL);
            }
            //更新统计值表
            sql="select id from t_job_stats_health where date_format(create_time,'%Y-%m-%d')=date_format(NOW(),'%Y-%m-%d')";
            List<Map<String, Object>> l=getJdbcTemplate().queryForList(sql);
            if(l!=null&&l.size()>0){
                //db update
                sql = "update t_job_stats_health  set Status_k8s=?,Status_harbor=?,Status_jenkins=?,Status_user_center=?,Status_app_center=?,Status_monitor_center=?,Status_log_center=?,Status_job_center=?,Status_help_center=?,Status_apiroute=?,Status_ci_center=?,last_update_time=NOW() where id=?";
                id=l.get(0).get("id").toString();
            }else{
                //db insert
                sql = "INSERT INTO t_job_stats_health(Status_k8s,Status_harbor,Status_jenkins,Status_user_center,Status_app_center,Status_monitor_center,Status_log_center,Status_job_center,Status_help_center,Status_apiroute,Status_ci_center,id,create_time,last_update_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())";
                id = StringUtil.getUUID();
            }
            objs.add(Status_k8s);
            objs.add(Status_harbor);
            objs.add(Status_jenkins);
            objs.add(Status_user_center);
            objs.add(Status_app_center);
            objs.add(Status_monitor_center);
            objs.add(Status_log_center);
            objs.add(Status_job_center);
            objs.add(Status_help_center);
            objs.add(Status_apiroute);
            objs.add(Status_ci_center);
            objs.add(id);
            getJdbcTemplate().update(sql, objs.toArray());
        }catch (Exception ex){
            logger.error(ex.getMessage(),ex);
            handleEx("统计平台健康任务异常,异常信息:"+getErrorInfoFromException(ex),Constants.ALARM_TYPE_JOB_ERROR,Constants.ALARM_STATUS_UN,Constants.ALARM_LEVEL_HIGHEST,Constants.ALARM_NS_ALL);
            throw new JobExecutionException(ex);
        }
    }


    private String getResult(String url,OkHttpClient httpClient) throws IOException {
        String result="";
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        result = response.body().string();
        return result;
    }
}